Practice Problems and Solutions

You should do these problems on paper or mentally first, and only THEN check the solution.

 

Infinite List Practice Problems


Can you predict what will happen with the following
expressions? Will it disappear forever (the technical term
is that it "diverges") or give an answer? Or both (meaning, give
a part of an answer and then diverge). Think about it,
make a prediction, and then verify with ghci.

NOTE: You can cancel output in ghci by typing control-c. In the worst
case if you are in a Unix system you can suspend the whole process
 using control-z and then kill it:

Prelude> nats = map (+1) nats
Prelude> nats
^Z
[1]+  Stopped                 ghci
HW11 $ kill %1

[1]+  Stopped                 ghci



Prelude> x = [1..]

--(i)

Prelude> head x

--(ii)

Prelude> tail x

--(iii)

Prelude> head (tail (tail x))

--(iv)

Prelude> zip x (tail x)

--(v)

Prelude> take 5 x

--(vi) 

Prelude> elem 100000 x

--(vii)

Prelude> elem (-3) x

--(viii)

Prelude> filter (<5) x

--(ix)

Prelude> takeWhile (<5) x

--(x)

Prelude> zzz = 0 : zzz

Prelude> take 5 zzz

--(xi)

Prelude> rep k = k : (rep k)

Prelude> take 5 (rep k)

--(xii)

Prelude> take 5 (zip x (tail x))

--(xiii)

Prelude> take 10 (x ++ x)

--(xiv)

Prelude> foldr (+) 0 x

--(xv)

Prelude> t = [x*2 | x <- t]

Prelude> take 10 t

--(xvi)

Prelude> t = 1:[x*2 | x <- t]

Prelude> take 10 t

--(xvii)

Prelude> t = ("0":["S("++x++")" | x <- t])

Prelude> take 5 t 

--(xviii)

Prelude> f n = 1:[x*n| x <- (f n)]

Prelude> take 5 (f 5)

--(xix1

Prelude> nats = map (+1) nats

Prelude> take 10 nats

--(xx)

Prelude> nats = 1:(map (+1) nats)

Prelude> take 10 nats